package com.snail.auth.action;

import com.common.ResultUtil;
import com.common.entity.BaseController;
import com.common.util.RedisUtil;
import com.snail.auth.JwtTokenUtil;
import com.snail.auth.entity.SecurityUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(description = "系统登录", tags = {"manage auth 0 login"})
@RestController
@Slf4j
@RequestMapping("")
public class AuthLoginController extends BaseController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Value("${token.salt}")
    private String salt;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 仅用于swagger显示，实际使用security默认登录方法
     */
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "登录账号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "string", paramType = "query")
    })
    @PostMapping("/login")
    public Map login(@RequestParam String username, @RequestParam String password) {
        //验证用户信息
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        SecurityUser user = (SecurityUser) authentication.getPrincipal();
        Map claims = new HashMap();
        claims.put("name", user.getUsername());
        claims.put("pwd", user.getPassword());
        String token = JwtTokenUtil.generateToken(user.getUsername(), 120, claims, salt);
        return ResultUtil.result(token);
    }

    @ApiOperation(value = "登出")
    @GetMapping("/logout")
    public void logout() {

    }
}
